function _start_change_style() {
    let cur_hour = myDate.getHours();
    const style_index = parseInt(localStorage.getItem("style"));
    if (style_index === 0) {
        article2Day();
    } else if (style_index === 1) {
        article2light();
    } else {
        if ((18 <= cur_hour && 24 >= cur_hour) || (0 <= cur_hour && 6 >= cur_hour)) {
            article2light();
        } else {
            article2Day();
        }
    }
    // $.ajax({
    //     type: "POST",
    //     data: {},
    //     url: flag_check_url,
    //     //这里用的是static url 需要与urls.py中的name一致
    //     cache: false,
    //     dataType: "html",
    //     async: true,
    //     success: function (result, statues, xml) {
    //         if (result) {
    //             const jsonData = JSON.parse(result);
    //             //alert(typeof jsonData['flag']) ;
    //             if (jsonData['flag'] === "-1") {
    //                 if ((18 <= cur_hour && 24 >= cur_hour) || (0 <= cur_hour && 6 >= cur_hour)) {
    //                     article2light();
    //                 } else {
    //                     article2Day();
    //                 }
    //             } else if (jsonData['flag'] === "0") {
    //                 article2Day();
    //             } else if (jsonData['flag'] === "1") {
    //                 article2light();
    //             }
    //         }
    //     },
    //     error: function (xhr, textStatus, errorThrown) {
    //         //window.location.reload() ;
    //         //alert("error:pls call the admin "+xhr.responseText);
    //     }
    // });
}

const myDate = new Date();
$(document).ready(function () {

    _start_change_style() ;
    $(function () {
        const cur_page = parseInt($(".page-cur").text());
        const tot_page = parseInt($(".page-tot").text());
        const min_page = Math.max(1, cur_page - 4);
        const max_page = Math.min(tot_page, cur_page + 4);
        for (let i = min_page; i <= max_page; ++i) {
            const new_jump = "<a class=\"page-jump\" " +
                "href=\"?page=" + i + "\">" + i + "</a>";
            $(".page-jump-list").append(new_jump);
        }
    });
    $(function () {
        const cur_page = parseInt($(".page-cur").text());
        const tot_page = parseInt($(".page-tot").text());
        const min_page = Math.max(1, cur_page - 4);
        const max_page = Math.min(tot_page, cur_page + 4);
        for (let i = min_page; i <= max_page; ++i) {
            if (i === cur_page) {
                const new_jump = "<a class=\"bottom-page-jump page-jump-hover\" " +
                    "href=\"" + "javascript:;" + "\">" + i + "</a>";
                $(".bottom-page-jump-list").append(new_jump);
            } else {
                const new_jump = "<a class=\"bottom-page-jump\" " +
                    "href=\"?page=" + i + "\">" + i + "</a>";
                $(".bottom-page-jump-list").append(new_jump);
            }
        }
    });
    $(".cur-page").click(function () {
        $(".page-jump-list").toggleClass("page-jump-list-show");
    });
    $(".night_sty,.day_sty").click(function () {
        //console.log($(this).index()) ;
        // $.ajax({
        //     type: "POST",
        //     data: {
        //         'style': $(this).index() - 1
        //     },
        //     url: flag_change_url,
        //     cache: false,
        //     dataType: "html",
        //     async: false,
        //     success: function (result, statues, xml) {
        //         if (result) {
        //         }
        //         updateStyle();
        //     }, error: function (xhr, textStatus, errorThrown) {
        //     }
        // });
        localStorage.setItem("style", ($(this).index() - 1).toString());
        updateStyle();
    });

    $(".email-show").click(function () {
        $(this).toggleClass("email-show-stop");
    });
    $(".cur-user").click(function () {
        $(".trun-out").toggleClass("roteYhidden");
        $(".logout").toggleClass("roteYhidden");
    });
    $(".moon-font").lzhDrag({
        startDown: function () {
        },
        startMove: function () {
        },
        overMove: function () {
        }
    }).html("");
    $(".moon-font").mousemove(function (e) {
        e = e || window.event;
        let cur_top = getDistance($(this)).top,
            cur_right = getDistance($(this)).right;
        let min_x = 0, max_x = 140,
            min_y = 0, max_y = 140;
        cur_right = cur_right < min_x ? min_x : cur_right;
        cur_right = cur_right > max_x ? max_x : cur_right;
        cur_top = cur_top < min_y ? min_y : cur_top;
        cur_top = cur_top > max_y ? max_y : cur_top;
        var target_x = 40, target_y = 40;
        var curDis = (cur_right - target_x) * (cur_right - target_x) + (cur_top - target_y) * (cur_top - target_y);
        var rate = 1 - curDis / 20000;
        rate *= 0.9;
        /*if (rate>=0.7) {
            article2light() ;
        } else {
            article2Day() ;
        }*/
        /*console.log(curDis) ;
        console.log(rate) ;
        console.log(cur_right+":"+cur_top) ;*/
        var curLightness = "5000px solid rgba(0, 0, 0," + rate + ")";
        $(".lightCover").css("outline", curLightness);
    });
    $(".moon-back").click(function () {
        startSakura();
    });
    $(".fake-info").click(function () {
        $(".fake-info").css("display", "none");
    });
    $(".cur-user").click(function () {
        $(".moon-light").toggleClass("moon-hidden");
        $(".moon-back").toggleClass("moon-hidden");
        $(".moon-font").toggleClass("moon-hidden");
    });
    $(window).scroll(function () {
        let totHeight = document.body.scrollHeight - window.innerHeight;
        let curRate = ($(document).scrollTop() / totHeight) * 100;
        var tmp = curRate.toString() + "%";
        $("#preogressbar").css("height", tmp);
    });

    let first_show_daily_news_list = true;
    $(".extra-screen-btn").click(function () {
        if (first_show_daily_news_list) {
            first_show_daily_news_list = false;
            set_daily_news_list();
        }
        $(".extra-screen").toggleClass("extra-screen-hidden");
    });
    set_tools_grid();

});

function article2light() {
    if ($("#base-css").length > 0 && $("#base-css").attr("href").indexOf("-dark") == -1) {
        $("#base-css").attr("href", $("#base-css").attr("href").replace(".css", "-dark.css"));
    }
    if ($("#index-css").length > 0 && $("#index-css").attr("href").indexOf("-dark") == -1) {
        $("#index-css").attr("href", $("#index-css").attr("href").replace(".css", "-dark.css"));
    }
    if ($("#detail-css").length > 0 && $("#detail-css").attr("href").indexOf("-dark") == -1) {
        $("#detail-css").attr("href", $("#detail-css").attr("href").replace(".css", "-dark.css"));
    }
    if ($("#_archives-css").length > 0 && $("#_archives-css").attr("href").indexOf("-dark") == -1) {
        $("#_archives-css").attr("href", $("#_archives-css").attr("href").replace(".css", "-dark.css"));
    }
    if ($("#_friend_link-css").length > 0 && $("#_friend_link-css").attr("href").indexOf("-dark") == -1) {
        $("#_friend_link-css").attr("href", $("#_friend_link-css").attr("href").replace(".css", "-dark.css"));
    }
    if ($("#_categories-css").length > 0 && $("#_categories-css").attr("href").indexOf("-dark") == -1) {
        $("#_categories-css").attr("href", $("#_categories-css").attr("href").replace(".css", "-dark.css"));
    }
}

function article2Day() {
    if ($("#base-css").length > 0 && $("#base-css").attr("href").indexOf("-dark") != -1) {
        $("#base-css").attr("href", $("#base-css").attr("href").replace("-dark", ""));
    }
    if ($("#index-css").length > 0 && $("#index-css").attr("href").indexOf("-dark") != -1) {
        $("#index-css").attr("href", $("#index-css").attr("href").replace("-dark", ""));
    }
    if ($("#detail-css").length > 0 && $("#detail-css").attr("href").indexOf("-dark") != -1) {
        $("#detail-css").attr("href", $("#detail-css").attr("href").replace("-dark", ""));
    }
    if ($("#_archives-css").length > 0 && $("#_archives-css").attr("href").indexOf("-dark") != -1) {
        $("#_archives-css").attr("href", $("#_archives-css").attr("href").replace("-dark", ""));
    }
    if ($("#_friend_link-css").length > 0 && $("#_friend_link-css").attr("href").indexOf("-dark") != -1) {
        $("#_friend_link-css").attr("href", $("#_friend_link-css").attr("href").replace("-dark", ""));
    }
    if ($("#_categories-css").length > 0 && $("#_categories-css").attr("href").indexOf("-dark") != -1) {
        $("#_categories-css").attr("href", $("#_categories-css").attr("href").replace("-dark", ""));
    }
}

function getDistance(obj) {
    if (!obj instanceof jQuery) {
        obj = $(obj);
    }
    var distance = {};
    distance.top = (obj.offset().top - $(document).scrollTop());
    distance.bottom = ($(window).height() - distance.top - obj.outerHeight());
    distance.left = (obj.offset().left - $(document).scrollLeft());
    distance.right = ($(window).width() - distance.left - obj.outerWidth());
    return distance;
}

function updateStyle() {
    // $.ajax({
    //     type: "POST",
    //     data: {},
    //     url: flag_check_url,
    //     //这里用的是static url 需要与urls.py中的name一致
    //     cache: false,
    //     dataType: "html",
    //     async: true,
    //     success: function (result, statues, xml) {
    //         if (result) {
    //             const jsonData = JSON.parse(result);
    //             //console.log(jsonData['flag']) ;
    //             if (jsonData['flag'] === "-1") {
    //             } else if (jsonData['flag'] === "0") {
    //                 article2Day();
    //             } else if (jsonData['flag'] === "1") {
    //                 article2light();
    //             } else {
    //                 console.log("anything");
    //             }
    //         } else {
    //             console.log("nothing");
    //         }
    //     },
    //     error: function (xhr, textStatus, errorThrown) {
    //         console.log("updateStyle error");
    //         //window.location.reload() ;
    //         //alert("error:pls call the admin "+xhr.responseText);
    //     }
    // });
    const style_index = parseInt(localStorage.getItem("style"));
    console.log(style_index);
    switch (style_index) {
        case 0 : {
            article2Day();
            break;
        }
        case 1 : {
            article2light();
            break;
        }
        default: {
            alert("Someting error in change style QAQ.")
        }
    }
    document.querySelectorAll(".tools-box").forEach((e) => {
        const cur_style = parseInt(localStorage.getItem("style"));
        if (cur_style === 0) {
            e.style.background = "rgba(178, 190, 195,.15)";
            e.style.borderImage = null;
            e.border = "1.5px solid rgba(99, 110, 114, .15)";
        } else if (cur_style === 1) {
            e.style.background = "rgba(0, 0, 0, 0.8)";
            e.style.borderImage = null;
            e.border = "1.5px solid rgba(255, 255, 255, .25)";
        }
    });
}

$.fn.extend({
    lzhDrag: function (obj) {
        let max_left = $(this).offsetParent().outerWidth() - $(this).outerWidth(),
            max_top = $(this).offsetParent().outerHeight() - $(this).outerHeight();
        $(this).on('mousedown', event => {
            let ele_x = event.offsetX,
                ele_y = event.offsetY;
            obj.startDown && obj.startDown();
            $(document).on('mousemove', e => {
                obj.startMove && obj.startMove();
                e.preventDefault();
                let left = e.clientX - ele_x,
                    top = e.clientY - ele_y;
                left = left < 0 ? 0 : left;
                top = top < 0 ? 0 : top;
                left = left > max_left ? max_left : left;
                top = top > max_top ? max_top : top;
                $(this).css({
                    left, top
                })
            })
        })
        $(document).on('mouseup', () => {

            $(document).off('mousemove');
            obj.overMove && obj.overMove();
        })
        return this;
    }
})

function _time_parse(time_str) {
    //var time = "2017-06-23 17:00:00";
    time_str = time_str.replace(/-/g, ":").replace(" ", ":").replace("T", ":");
    // 注意，第二个replace里，是' '，中间有个空格，千万不能遗漏
    time_str = time_str.split(":");
    var time1 = new Date(time_str[0], (time_str[1] - 1), time_str[2], time_str[3], time_str[4], time_str[5]);
    var time2 = new Date().getDate();
    const dif_days = time_str[2] - time2;
    let day_status = time_str[0] + "-" + time_str[1] + "-" + time_str[2] + " ";
    if (dif_days === 0) {
        day_status = "今日 ";
    } else if (dif_days === 1) {
        day_status = "昨日 ";
    } else if (dif_days === 2) {
        day_status = "两日前 ";
    }

    day_status += time_str[3] + ":" + time_str[4];
    return day_status
}

function _set_status_color(status) {
    switch (status) {
        case "normal" :
            return "rgba(0, 184, 148,1.0)";
        case "人麻了":
            return "#eb6238";
        case "TMD":
            return "rgba(214, 48, 49,1.0)";
        case "人没了":
            return "rgba(0,0,0,0)";
        case "疑惑":
            return "rgba(9, 132, 227,1.0)";
        case "啥玩意":
            return "rgba(9, 132, 227,1.0)";
        case "重伤倒地":
            return "rgba(45, 52, 54,1.0)";
        case "wocao":
            return "rgba(214, 48, 49,1.0)";
        case "dokidoki":
            return "#f09199";
    }
}

function set_tools_grid() {

    const offset = 68;
    const angles = []; //in deg
    for (let i = 0; i <= 360; i += 30) {
        angles.push((i * Math.PI) / 180);
    }
    let nearBy = [];

    function clearNearBy() {
        nearBy.splice(0, nearBy.length).forEach((e) => (e.style.borderImage = null));
    }

    /*Effect #1 - https://codepen.io/struct_dhancha/pen/QWdqMLZ*/
    document.querySelectorAll(".tools-box").forEach((b) => {

        b.onmouseleave = (e) => {
            // e.target.style.background = "rgba(0,0,0,0)";
            // e.target.style.borderImage = null;
            // e.target.border = "1px solid transparent";
            const cur_style = parseInt(localStorage.getItem("style"));
            if (cur_style === 0) {
                e.target.style.background = "rgba(178, 190, 195,.15)";
                e.target.style.borderImage = null;
                e.target.border = "1.5px solid rgba(99, 110, 114, .15)";
            } else if (cur_style === 1) {
                e.target.style.background = "rgba(0, 0, 0, 0.8)";
                e.target.style.borderImage = null;
                e.target.border = "1.5px solid rgba(255, 255, 255, .25)";
            }

        };

        b.onmouseenter = (e) => {
            clearNearBy();
        };

        b.addEventListener("mousemove", (e) => {
            const cur_style = parseInt(localStorage.getItem("style"));
            b.border = "1px solid transparent";
            const rect = b.getBoundingClientRect();
            const x = e.clientX - rect.left; //x position within the element.
            const y = e.clientY - rect.top; //y position within the element.
            // b.style.background = `radial-gradient(circle at ${x}px ${y}px , rgba(255,255,255,0.25),rgba(255,255,255,0) )`;
            // b.style.borderImage = `radial-gradient(20% 65% at ${x}px ${y}px ,rgba(255,255,255,0.7),rgba(255,255,255,0.7),rgba(255,255,255,0.1) ) 9 / 2px / 0px stretch `;
            if (cur_style === 0) {
                b.style.background = `radial-gradient(circle at ${x}px ${y}px , rgba(225, 112, 85, 0.25) ,rgba(176,213,223,0) )`;
                b.style.borderImage = `radial-gradient(20% 65% at ${x}px ${y}px ,rgba(225, 112, 85,0.7),rgba(225, 112, 85,0.7), rgba(225, 112, 85,0.1) ) 9 / 2px / 0px stretch `;
            } else if (cur_style === 1) {
                b.style.background = `radial-gradient(circle at ${x}px ${y}px , rgba(225, 255, 255, 0.25) ,rgba(255,255,255,0) )`;
                b.style.borderImage = `radial-gradient(20% 65% at ${x}px ${y}px ,rgba(255,255,255,0.7),rgba(255,255,255,0.7), rgba(255,255,255,0.1) ) 9 / 2px / 0px stretch `;
            }

            // e.target.border = "1px solid transparent";
            // const rect = e.target.getBoundingClientRect();
            // const x = e.clientX - rect.left; //x position within the element.
            // const y = e.clientY - rect.top; //y position within the element.
            // e.target.style.background = `radial-gradient(circle at ${x}px ${y}px , rgba(255,255,255,0.25),rgba(255,255,255,0) )`;
            // e.target.style.borderImage = `radial-gradient(20% 65% at ${x}px ${y}px ,rgba(255,255,255,0.7),rgba(255,255,255,0.7),rgba(255,255,255,0.1) ) 9 / 2px / 0px stretch `;
        });
    });

    const body = document.querySelector(".extra-screen");

    body.addEventListener("mousemove", (e) => {

        const x = e.x; //x position within the element.
        const y = e.y; //y position within the element.
        clearNearBy();
        nearBy = angles.reduce((acc, rad, i, arr) => {
            const cx = Math.floor(x + Math.cos(rad) * offset);
            const cy = Math.floor(y + Math.sin(rad) * offset);
            const element = document.elementFromPoint(cx, cy);

            if (element !== null) {

                if (
                    // element.className === "tools-box"
                    element.className.indexOf("tools-box") !== -1
                    //&& acc.findIndex((ae) => ae.id === element.id) < 0
                ) {
                    //console.log(element.id)
                    const brect = element.getBoundingClientRect();
                    const bx = x - brect.left; //x position within the element.
                    const by = y - brect.top; //y position within the element.

                    // element.style.borderImage = `radial-gradient(${offset * 2}px ${
                    //     offset * 2
                    // }px at ${bx}px ${by}px ,rgba(255,255,255,0.7),rgba(255,255,255,0.1),transparent ) 9 / 2px / 0px stretch `;
                    //
                    const cur_style = parseInt(localStorage.getItem("style"));
                    if (cur_style === 0) {
                        element.style.borderImage = `radial-gradient(${offset * 2}px ${
                            offset * 2
                        }px at ${bx}px ${by}px ,rgba(225, 112, 85,0.7), rgba(225, 112, 85,0.1),transparent ) 9 / 2px / 0px stretch `;
                    } else if (cur_style === 1) {
                        element.style.borderImage = `radial-gradient(${offset * 2}px ${
                            offset * 2
                        }px at ${bx}px ${by}px ,rgba(255, 255, 255,0.7), rgba(255, 255, 255,0.1),transparent ) 9 / 2px / 0px stretch `;
                    }

                    return [...acc, element];
                }
            }
            return acc;
        }, []);

    });

    body.onmouseleave = (e) => {
        clearNearBy();
    };
}

function set_daily_news_list() {
    $.ajax({
        type: "POST",
        data: {},
        url: get_daily_news_list_url,
        //这里用的是static url 需要与urls.py中的name一致
        cache: false,
        dataType: "html",
        async: true,
        success: function (result, statues, xml) {
            if (result) {
                const json_data = JSON.parse(result);
                let ul_daily_news_list = $("ul.daily_news_list");
                let post_list = JSON.parse(json_data["post_list"]);

                post_list.forEach(function (element, index, array) {
                    ul_daily_news_list.append(
                        `<li class=\"daily_news\">
                           <div class=\"news-info\">
                               <img id=\"head-img\" src=\"${daily_news_head_img_list[index]}\"
                                    alt=\"\"/>
                               <div class=\"right-info\">
                                   <div class=\"autor-status\">
                                       <span class=\"autor\">
                                           R0
                                       </span>
                                       <span class=\"status\" style="background:${_set_status_color(element.fields.status)}">
                                           ${element.fields.status}
                                       </span>
                                   </div>
                                   <div class=\"time-describe\">
                                       ${_time_parse(element.fields.created_time)}
                                   </div>
                                   <div class="other-info">
                                       <i class="iconfont icon-Coffeeteacuplikelove" idurl="${news_like_url.replace("000000", element.pk)}">
                                            <span class="news-pk">
                                                ${element.fields.like_cnt}
                                            </span>
                                       </i>
                                       <span class=\"news-title\">
                                           ${element.fields.title}
                                       </span>
                                   </div>
                               </div>
                           </div>
                           
                           <p class=\"news-body\">
                               ${element.fields.body}
                           </p>
                       </li>`
                    );
                });
                $(".daily_news .news-info .right-info .other-info .icon-Coffeeteacuplikelove").click(function () {
                    const news_id_url = $(this).attr("idurl");
                    $this_span = $(this).children(".news-pk");
                    $.ajax({
                        type: "POST",
                        data: {},
                        url: news_id_url,
                        //这里用的是static url 需要与urls.py中的name一致
                        cache: false,
                        dataType: "html",
                        async: true,
                        success: function (result, statues, xml) {
                            if (result) {
                                const json_data = JSON.parse(result);
                                const news_like_cnt = json_data["news_like_cnt"];
                                $this_span.text(news_like_cnt);
                            } else {
                                console.log("nothing");
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            console.log("like error");
                        }
                    });
                })
            } else {
                console.log("nothing");
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log("updateStyle error");
            //window.location.reload() ;
            //alert("error:pls call the admin "+xhr.responseText);
        }
    });
}